// index page
// ============

define(['zepto', 'utils', 'wxpay', 'sui', 'countDown' ], function($, utils, wxpay) {
      return {
        init : function(data) {
          this.unionid = data.unionid;
          this.userId = data.userId;
          this.betId = data.betId;
          this.token = null;
          utils.configWeixin(data.jsConfig, false);
          this.bindMobileBindingPageEvent()
          this.bindCreateOrder();
        },
        
        bindCreateOrder: function() {
          var that = this;
          $(document).on('click', '#submit', function(e) {
            e.preventDefault();
            
            $.showPreloader('正在提交订单')
            //api.host=http://127.0.0.1:8085/fitbet-api
            $.post(window.__CTX__.root + '/profile/bets?betId=' + that.betId)
            .done(function(response) {
              $.hidePreloader();
              utils.processResult(response, function(data) {
                that.configWxPay(data)
              }, function() {
                $.toast(result.message || '订单提交失败')
              })
            })
          })
        },
        
        configWxPay: function(result) {
          
          $.showPreloader('正在提交支付数据')
          console.log(result);
          
          var that = this,
              order = result.data.salesOrder.id;
          
          var submiting = that.requestPayConfig(order);
          
          $.when(submiting).done(function(data, order) {
            $.hidePreloader();
            wxpay.injectConfig(data.jsConfig, ['chooseWXPay'])
            wxpay.invokePay(data.payConfig, function(res) {
              setTimeout(function() {
                  window.location.href= window.__CTX__.root + "/shopping/result?orderId=" + order;
              }, 1000)
            })
          })
        },
        
        requestPayConfig: function(order) {
          $.showPreloader('正在提交支付数据')
          var that = this, defer = $.Deferred()
          $.post(window.__CTX__.root + '/shopping/pay', {
            'order': order,
            'currentUrl': window.location.href
           }).done(function(response) {
              utils.processResult(response, function(result) {
                $.hidePreloader()
                defer.resolve(result.data, order)
              }, function(result) {
                $.hidePreloader()
                $.toast(result.message || '请求支付数据失败')
                setTimeout(function() {
                  window.location.reload();
                }, 1000);
              })
            })
            
          return defer.promise()
        },
        
        bindMobileBindingPageEvent : function() {
          var that = this,
            $mobile = $('input[name="mobile"]'),
            $code = $('input[name="code"]');
        
          $(document).on('click', '.get-code', function(e) {
            e.preventDefault()
              
            var $button = $(e.currentTarget), 
                $verfyModal = $("verfyModal");
                mobile = $mobile.val().trim();
            
            if (that.isMobile(mobile)) {
                // Disable button
                $button.css('pointer-events', 'none')
                // Request verifiy code
                that.requestVerifyCode(mobile, function(data) {
                  
                  that.token = data.token;
                  
                  $button.countdown('s后重试', 60, function() {
                    $button.css('pointer-events', 'initial').text('获取验证码')
                  })
                  
                  $.modal({
                    extraClass: 'verfy-modal',
                    title:  '请输入验证码',
                    text: 
                      '<div id="verfy-error" class="verfy-error hide">请输入正确的验证码</div>'+
                      '<input type="number" name="code" class="code-grid" />'+
                      '<input type="number" name="code" class="code-grid" />'+
                      '<input type="number" name="code" class="code-grid" />'+
                      '<input type="number" name="code" class="code-grid" />'+
                      '<input type="number" name="code" class="code-grid" />'+
                      '<input type="number" name="code" class="code-grid" />',
                    buttons: [{
                      text: '确定',
                      onClick: function() {
                        var submitingStatus = $(this).data("submiting");
                        if(submitingStatus != "true") {
                          var mobile = $mobile.val().trim();
                          var codes = []
                          if (!that.isMobile(mobile)) return $.toast('请输入正确的手机号码')
                          $("input[name='code']").each(function(){
                            if(!$(this).val()) {
                              $("#verfy-error").html("验证码不能为空").removeClass("hide");
                              return
                            } else {
                              console.log($(this).val())
                              codes.push($(this).val())
                            }
                          })
                          
                          var code = codes.join('');
                          that.code = code;
                          var submiting = that.submitMobile(mobile, code)
                          $.when(submiting).done(function(data) {
                            if(data.redirect && data.redirect != '/') {
                              window.location.href = window.__CTX__.root + data.redirect;
                            } else {
                              window.location.href = window.__CTX__.root + "/shopping?sku=" + that.sku + "&showRules=false";
                            }
                          })
                        }
                        
                      }
                    }]
                  })
                  
                  var codeInputs = $("input[name='code']");
                  for(var i = 0; i < codeInputs.length; i++) {
                    console.log(codeInputs[i]);
                    var t = codeInputs[i];
                        t.index = i;
                        t.setAttribute("readonly", true);
                        t.onkeyup=function(){
                          console.log(this);
                          this.value=this.value.replace(/^(.).*$/,'$1');
                          var next = this.index + 1;
                          $(codeInputs[next]).removeAttr("readonly");
                          $(codeInputs[next]).focus();
                        }
                  }
                  
                  $(codeInputs[0]).removeAttr("readonly")
                  
                }, function() {
                  $button.css('pointer-events', 'initial')
                })
              } else {
                $.toast('请输入正确的手机号码')
              }
            })
        },
        
        isMobile: function(mobile) {
          return mobile && /^((16)|(13)|(15)|(17)|(18))\d{9}$/.test(mobile)
        },
        
        requestVerifyCode: function(mobile, success, failure) {
          $.showIndicator()
          utils.requestVerifyCode(mobile, function(result) {
            $.hideIndicator()
            $.toast('验证码发送成功')
            success && success(result.data)
          }, failure)
        },
        
        submitMobile: function(mobile, code) {
          var that = this, defer = $.Deferred();
          

          $.post(window.__CTX__.root + '/login', {'mobile': mobile, 'code': code, 'token': that.token, 'unionid': that.unionid})
            .done(function(response) {
              $.hideIndicator()
              utils.processResult(response, function(result) {
                $.toast(result.message || '验证成功')
                defer.resolve(result.data)
                window.location.reload();
              }, function(result) {
                $("#submit").data("submiting", "false");
                $.toast(result.message || '手机认证失败')
              })
            })
              
          return defer.promise()
        }
      }
    })